/**
Copyright (c) 2008 New Gonzo <john@newgonzo.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/


﻿package com.newgonzo.cannonball.browser.dom
{
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;
	
	import com.newgonzo.commons.logging.Log;
	import com.newgonzo.commons.logging.ILogger;
	
	import com.newgonzo.cannonball.w3c.dom.*;
	import com.newgonzo.cannonball.w3c.dom.views.IAbstractView;
	import com.newgonzo.cannonball.w3c.dom.views.IDocumentView;
	import com.newgonzo.cannonball.w3c.dom.traversal.*;
	
	import com.newgonzo.cannonball.dom.*;
	import com.newgonzo.cannonball.dom.css.ICSSStylableElement;
	
	import com.newgonzo.cannonball.browser.context.IContext;
	import com.newgonzo.cannonball.browser.actions.IAction;
	import com.newgonzo.cannonball.browser.rendering.*;
	
	import com.newgonzo.cannonball.browser.dom.DOMContext;
	
	public class DOMRendering implements IRendering, INodeFilter
	{
		protected static const log:ILogger = Log.getLogger(DOMRendering);
		
		private var context:IContext;
		
		private var contentRenderers:Dictionary;
		private var rendererContent:Dictionary;
		
		private var display:Array;
		private var contents:Array;
		
		private var rendererParents:Dictionary;
		private var parentRenderers:Dictionary;
		
		
		public function DOMRendering(context:IContext)
		{
			this.context = context;
		}
		
		public function fetch(content:Object):IRenderer
		{
			return contentRenderers[content];
		}
		
		public function fetchAll(content:Object):Array
		{
			return display.concat();
		}
		
		public function fetchChildren(content:Object):Array
		{
			log.debug("DOMRendering.fetchChildren(" + content + ")");
			
			var display:Array = parentRenderers[content.style.getPropertyValue("-ng-renderer")] as Array;
			
			if(display)
			{
				//display.sort(rendererSortFunc);
				return display.concat();
			}
			
			return new Array();
		}
		
		public function render(document:Object):void
		{
			log.debug("DOMRendering.render(" + document + ")");
			
			try
			{
				clearRenderers();
				
				contentRenderers = new Dictionary(true);
				rendererContent = new Dictionary(true);
				
				rendererParents = new Dictionary(true);
				parentRenderers = new Dictionary(true);
				
				display = new Array();
				contents = new Array();
				
				var rendererName:String;
				var renderer:IRenderer;
				var parentNode:INode;
				var parent:String;
				var policy:String;
				
				var walker:ITreeWalker = document.createTreeWalker(document.documentElement as INode, 0, this);
				
				var content:Object = walker.nextNode();
				
				while(content)
				{
					// try to render
					rendererName = content.style.getPropertyValue("-ng-renderer");
					
					if(rendererName == "none")
					{
						content = walker.nextNode();
						continue;
					}
					
					renderer = context.view.getRenderer(rendererName);
					
					if(!renderer)
					{
						content = walker.nextNode();
						continue;
					}
					
					// set renderer parent
					renderer.rendering = this;
					
					parent = content.style.getPropertyValue("-ng-renderer-parent");
					
					if(!parent.length)
					{
						parentNode = walker.parentNode();
						
						if(parentNode)
						{
							parent = (parentNode as ICSSStylableElement).style.getPropertyValue("-ng-renderer");
						}
						
						// reset walker
						walker.currentNode = content as INode;
					}
					
					// cache relationship
					if(parent.length)
					{
						setRendererParent(renderer, parent);
					}
					
					// set context here so display have an opportunity to register other display
					renderer.context = context;
					
					contentRenderers[content] = renderer;
					rendererContent[renderer] = content;
					contents.push(content);
					
					content = walker.nextNode();
				}
				
				contents.sort(contentSortFunc);
				
				for each(var c:Object in contents)
				{
					trace(c.style.getPropertyValue("-ng-renderer"));
				}
				
				// loop again to initialize created display
				for each(content in contents)
				{
					renderer = contentRenderers[content];
					display.push(renderer);
					renderer.content = content;
				}
			}
			catch(e:Error)
			{
				log.error(e.toString());
			}
		}
		
		public function acceptNode(node:INode):uint
		{
			var rendererValue:String = (node as ICSSStylableElement).style.getPropertyValue("-ng-renderer");
			
			if(rendererValue == "skip")
			{
				return NodeFilter.FILTER_SKIP;
			}
			
			if(rendererValue == "reject")
			{
				return NodeFilter.FILTER_REJECT;
			}
			
			if(rendererValue != "")
			{
				log.debug("Accepting rendered node " + node);
				return NodeFilter.FILTER_ACCEPT;
			}
			
			return NodeFilter.FILTER_SKIP;
		}
		
		private function setRendererParent(renderer:IRenderer, parent:String):void
		{
			if(!parentRenderers[parent])
			{
				parentRenderers[parent] = new Array();
			}
			
			parentRenderers[parent].push(renderer);
			rendererParents[renderer] = parent;
		}
		
		private function contentSortFunc(content1:Object, content2:Object):int
		{
			var pos:uint = (content1 as INode).compareDocumentPosition(content2 as INode);
			
			switch(pos)
			{
				case DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY:
				case DocumentPosition.DOCUMENT_POSITION_PRECEDING:
					return -1;
					
				case DocumentPosition.DOCUMENT_POSITION_CONTAINS:
				case DocumentPosition.DOCUMENT_POSITION_FOLLOWING:
					return 1;
					
				default:
					return 0;
			}
			
			return 0;
		}
		
		private function rendererSortFunc(renderer1:IRenderer, renderer2:IRenderer):int
		{
			var idx1:int = contents.indexOf(renderer1.content);
			var idx2:int = contents.indexOf(renderer2.content);
			
			if(idx1 < idx2)
			{
				return -1;
			}
			
			if(idx2 > idx1)
			{
				return 1;
			}
			
			return 0;
		}
		
		private function clearRenderers():void
		{
			var rend:IRenderer;
			
			for each(rend in display)
			{
				rend.content = null;
			}
		}
	}
}